#! /usr/bin/env python3
# -*- encoding:utf-8 -*-
import functools
from model.user import User
from model.blog import Blog
from page import Page
import time
import util
import helper.apiexception as apiex


def get(path):
    'get请求'

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            return func(*args, **kw)

        wrapper.__method__ = 'GET'
        wrapper.__route__ = path
        return wrapper

    return decorator


def post(path):
    'post请求'

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            return func(*args, **kw)

        wrapper.__method__ = 'POST'
        wrapper.__route__ = path
        return wrapper

    return decorator


@get("/api/users")
async def user(request, **kw):
    user = User()
    page = Page(curPage=kw.get('curPage', 1), pageSize=kw.get('pageSize', 10))
    userPage = await user.findPage(page)
    if userPage.curSize <= 0:
        raise apiex.APINotFoundException(message="未找到数据")
    return util.object2dict(userPage)


@get("/")
async def index(request):
    summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, \
        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'

    blogs = [
        Blog(
            id='1',
            name='Test Blog',
            summary=summary,
            created_at=time.time() - 120),
        Blog(
            id='2',
            name='Something New',
            summary=summary,
            created_at=time.time() - 3600),
        Blog(
            id='3',
            name='Learn Swift',
            summary=summary,
            created_at=time.time() - 7200)
    ]
    return {'__template__': 'blogs.html', 'blogs': blogs}


@get("/register")
async def register(request):
    return {'__template__': 'register.html'}


@post("/api/register")
async def registerApi(*, name, password, email):
    if not name or not name.strip():
        raise apiex.APIParamException(message='名称不能为空')
    if not password or not util.checkPwd(password):
        raise apiex.APIParamException(message='密码格式错误')
    if not email or not util.checkEmail(email):
        raise apiex.APIParamException(message='邮箱格式错误')
    user = User(email=email)
    count = await user.findCount()
    if count > 0:
        raise apiex.APIException(
            error="data:exist", message="邮箱已经注册过", data="email")
    uid = util.next_id()
    usernew = User(
        id=uid,
        name=name,
        passwd=util.genaratePwd(uid, password),
        email=email,
        image=util.avataHeadImg(email))
    await usernew.saveWithkey()
    usernew.passwd = '******'
    return usernew
